<?php
namespace app\wechat\controller;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use app\common\library\wechat\Wechat as WechatService;
use app\common\library\wechat\Config as ConfigService;
use think\Log;
use think\Db;
use think\Controller;

/**
 * 微信接口
 */
class Index extends Controller{
    public function index()
    {
        
    }

    /**
     * 微信API对接接口
     */
    public function api(){
		    $this->app = new Application(ConfigService::load());
			$this->app->server->setMessageHandler(function ($message) {	
			$config=F('_data/wechatconfig_cache');
            $WechatService = new WechatService;
            $openid = $message->FromUserName;
            $to_openid = $message->ToUserName;
            $event = $message->Event;
            $eventkey = $message->EventKey ? $message->EventKey : $message->Event;
            $unknownmessage = $config['wechat_errormsg'] ? $config['wechat_errormsg'] : "抱歉没有找到相关内容，请输入帮助";
			$defaultmsg = $config['wechat_defaultmsg'] ? $config['wechat_defaultmsg'] : "欢迎关注我们";
            switch ($message->MsgType){
                case 'event': //事件消息
                    switch ($event){
                        case 'subscribe'://添加关注
                            return $defaultmsg;
                        case 'unsubscribe'://取消关注
                            return '';
                        case 'LOCATION'://获取地理位置
                            return '';
                        case 'VIEW': //跳转链接,eventkey为链接
                            return '';
                        default:
                            break;
                    }
                    $response = Db::name('wechat_response')->where(['response_eventkey' => $eventkey, 'response_status' =>1])->find();
					if ($response){
                        $context = Db::name('wechat_context')->where(['openid' => $openid])->find();
                        $data = ['eventkey' => $eventkey, 'command' => '', 'refreshtime' => time(), 'openid' => $openid];
                        if ($context){
							Db::name('wechat_context')->where('id', $context['id'])->update($data);
                            $data['response_id'] = $context['id'];
                        }
                        else{
                            $id = Db::name('wechat_context')->insertGetId($data);
                            $data['response_id'] = $id;
                        }
                        $result = $WechatService->command($message,$response);
                        if ($result){
                            return $result;
                        }
                    }
                    return $unknownmessage;
                case 'text': //文字消息
                case 'image': //图片消息
                case 'voice': //语音消息
                case 'video': //视频消息
                case 'location': //坐标消息
                case 'link': //链接消息
                default: //其它消息
                    //上下文事件处理
                    // $context = Db::name('wechat_context')->where(['openid' => ['=', $openid], 'refreshtime' => ['>=', time() - 1800]])->find();
					// if ($context && $context['eventkey']){
                        // $response = Db::name('wechat_response')->where(['response_eventkey' => $context['eventkey'], 'response_status' =>1])->find();
                        // if ($response){
                            // Db::name('wechat_context')->data(array('refreshtime' => time()))->where('id', $context['id'])->update();
                            // $result = $WechatService->command($message,$response);
                            // if ($result){
                                // return $result;
                            // }
                        // }
                    // }
                    //自动回复处理
                    if ($message->MsgType == 'text'){
                        $result = $WechatService->msg($message);
                        if ($result){
                            return $result;
                        }
                    }
                    return $unknownmessage;
            }
            return ""; //SUCCESS
        });
        $response = $this->app->server->serve();
        // 将响应输出
        $response->send();
    }

    /**
     * 登录回调
     */
    public function callback(){
	$context = Db::name('WechatContext')->where('id',1)->find();
    // $this->app = new Application(ConfigService::load());		
    // $this->app->server->setMessageHandler(function ($message) {
    // return "您好！欢迎关注我!";
    // });
    // $response = $this->app->server->serve();
    // $response->send(); 	
    }

    /**
     * 支付回调
     */
    public function notify()
    {
        Log::record(file_get_contents('php://input'), "notify");
        $response = $this->app->payment->handleNotify(function($notify, $successful) {
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $orderinfo = Order::findByTransactionId($notify->transaction_id);
            if ($orderinfo)
            {
                //订单已处理
                return true;
            }
            $orderinfo = Order::get($notify->out_trade_no);
            if (!$orderinfo)
            { // 如果订单不存在
                return 'Order not exist.'; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            // 如果订单存在
            // 检查订单是否已经更新过支付状态,已经支付成功了就不再更新了
            if ($orderinfo['paytime'])
            {
                return true;
            }
            // 用户是否支付成功
            if ($successful)
            {
                // 请在这里编写处理成功的处理逻辑

                return true; // 返回处理完成
            }
            else
            { // 用户支付失败
                return true;
            }
        });

        $response->send();
    }

}
